import { routerRedux } from 'dva/router'
import { login, retrieveUserPwd } from 'services/login'
import { config } from 'utils'
import { message } from 'antd'
import md5 from '../routes/login/md5'

const { prefix } = config

export default {

  namespace: 'login',

   state: {
     register:false
    },

  effects: {
    //TODO: 登录函数，调用call login API获取用户数据和菜谱数据.
    * login({
      payload,
    }, { put, call, select }) {

      let { remember, username, password } = payload
      delete payload.remember
      // payload.password = md5(payload.password)
      // console.log(payload)
      
      //TODO: 调用login API
      const data = yield call(login, payload)
      console.log(data.data)
      //REMARK: 本地存储用户菜单数据
      window.localStorage.setItem(`${prefix}menus`, JSON.stringify(data.data.functionList))
      //TODO: 登录成功 data code为0
      if (data.code === '3') {
        // 记住密码
        // if (remember) {
        //   localStorage.setItem('password', password)
        //   localStorage.setItem('username', email)
        // } else {
        //   localStorage.setItem('password', '')
        //   localStorage.setItem('username', '')
        // }

        //REMARK: 本地存储用户tokenId
        // sessionStorage.setItem('tokenid', data.data.userInfo.tokenid);
        // sessionStorage.setItem('username', data.data.userInfo.userName);
        // sessionStorage.setItem('email', data.data.userInfo.email);
        // sessionStorage.setItem('userId', data.data.userInfo.userId);
        // sessionStorage.setItem('roleId', data.data.userInfo.roleId);
        // sessionStorage.setItem('userInfo', JSON.stringify(data.data.userInfo));

        
        // window.localStorage.setItem('menus',data.data);
        yield put(routerRedux.push('/chzu/peopleManage'));
        sessionStorage.setItem('code',data.code);
        // if (data.data.userInfo.roleId === 8) {
        //   //REMARK: 路由跳转到食材列表主页面
        //   yield put(routerRedux.push('/bshrecipes/foodManage/foodList'))
        // } else {
        //   //REMARK: 路由跳转到主页面
          
        // }
        message.success(data.msg);
      } else if(data.code === '1'){
        console.log(data.code)
        sessionStorage.setItem('code', data.code);
        yield put(routerRedux.push('/chzu/notreatList'));
      }else if(data.code === '2'){
        sessionStorage.setItem('code', data.code);
        yield put(routerRedux.push('/chzu/notreatList'));
      }else{

      }
    },

    * retrieveUserPwd({
      payload,
    }, { put, call, select }) {
      const data = yield call(retrieveUserPwd, payload)
      if (data.success) {
        message.info(data.msg)
      }
    }
  },
  reducer:{
    updateRegister(state,{payload}){
      return {
        ...state,
        register:payload
      }
    }
  }
}
